# -*- coding: utf-8 -*-
"""
Created on Wed Nov 23 20:14:14 2022

@author: LUO
"""
import subprocess
import os
import shutil
from ui_WidgetCopyData import Ui_WidgetCopyData

from PyQt5 import QtWidgets, QtGui, QtCore, QtGui

class pageCoyData(QtWidgets.QWidget, Ui_WidgetCopyData):

   MOUNT_DIR = "/media/usb_disk"

   def __init__(self, parent=None, index=0, keyBoard_callback=None):
      super(pageCoyData, self).__init__(parent)
      self.setupUi(self)

      self.setFont(QtGui.QFont('times', 14, QtGui.QFont.Black))
      
      self.BtnRefresh.clicked.connect(self.getDeviceList)
      self.BtnStartCpy.clicked.connect(self.cpyDataFiles)

      self.devInfoList = []
      self.devUuidList = []

   def getDeviceList(self):
      self.devInfoList = []
      self.devUuidList = []
      self.ComboWidgetList.clear()

      stat, output = subprocess.getstatusoutput("blkid | grep /dev/sda | grep -v boot")
      if stat != 0:
         self.LabStatus.setText("Read u disk list error!")
         return

      if len(output) < 5:
         self.LabStatus.setText("No disk found!")
         return

      dev_list = output.split("\n")
      for usb_device in dev_list:
         self.devUuidList.append(self.uuid_from_line(usb_device))
         self.devInfoList.append(usb_device)

      self.ComboWidgetList.addItems(self.devInfoList)
      self.ComboWidgetList.setCurrentIndex(0)

      self.LabStatus.setText("Please select a disk from the list!")

   def cpyDataFiles(self):
      if not os.path.exists(self.MOUNT_DIR):
         os.mkdir(self.MOUNT_DIR)

      if self.devInfoList == []:
          self.LabStatus.setText("The list is blank!")
          return

      index = self.ComboWidgetList.currentIndex()
      command = "mount --uuid %s %s" % (self.devUuidList[index], self.MOUNT_DIR)
      stat, output = subprocess.getstatusoutput(command)
      if stat != 0 and stat !=32:
          self.LabStatus.setText("Mount u disk list error, code=%d! \n -- %s"%(stat,output))
          return

      self.copyDir(src="./Data", dst=self.MOUNT_DIR+"/Data")
      self.LabStatus.setText("Data copy done!")

   def uuid_from_line(self, line):
      print(line)
      start_str = "UUID=\""
      example_uuid = "6784-3407"
      uuid_start = line.index(start_str) + len(start_str)
      uuid_end = uuid_start + len(example_uuid)
      return line[uuid_start: uuid_end]

   def copyDir(self, src='', dst=''):
      if not os.path.exists(dst):
         os.mkdir(dst)
      for f in os.listdir(src):
         if os.path.isfile(os.path.join(src, f)):
            shutil.copy(os.path.join(src, f), os.path.join(dst, f))
         else:
            self.copyDir(os.path.join(src, f), os.path.join(dst, f))





